package com.zhoux.springbucks.service;

import com.zhoux.springbucks.mapper.CoffeeMapper;
import com.zhoux.springbucks.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CoffeeService2 {
    @Autowired
    private CoffeeMapper coffeeMapper;

    @Autowired
    private RedisTemplate<String, Coffee> redisTemplate;

    /**
     * 查询单条coffee
     * @param id
     * @return
     */
    public Coffee findOneCoffee(long id) {
        Coffee coffee = coffeeMapper.selectByPrimaryKey(id);
        log.info("Coffee Found: {}", coffee);
        return coffee;
    }

    /**
     * 所有coffee，放入redis
     * @return
     */
    public List<Coffee> findAllCoffee() {
        List<Coffee> coffeeList = new ArrayList<>();
        if (redisTemplate.hasKey("springbucks-coffee-list")) {
            coffeeList = redisTemplate.opsForList().range("springbucks-coffee-list",0,-1);
            log.info("Redis get coffeeList Found: {}", coffeeList);
        } else {
            coffeeList = coffeeMapper.selectByExample(null);
            if (!CollectionUtils.isEmpty(coffeeList)) {
                redisTemplate.opsForList().rightPushAll("springbucks-coffee-list", coffeeList);
                redisTemplate.expire("springbucks-coffee-list", 1, TimeUnit.MINUTES);
                log.info("H2 coffeeList Found: {}", coffeeList);
            }
        }
        log.info("coffeeList Found: {}", coffeeList);
        return coffeeList;
    }

    @Transactional
    public void creatOneCoffee(Coffee coffee) {
        log.info("Coffee Add: {}", coffee);
        coffeeMapper.insert(coffee);
        log.info("Add success");
    }

    @Transactional
    public void updateOneCoffee(Coffee coffee) {
        log.info("Coffee update: {}", coffee);
        coffeeMapper.updateByPrimaryKey(coffee);
        log.info("update success");
    }

    @Transactional
    public void delOneCoffee(long id) {
        log.info("Coffee delete: {}", id);
        coffeeMapper.deleteByPrimaryKey(id);
        log.info("delete success");
    }

    public List<Coffee> pageFind(@Param("pageNum") int pageNum,
                                 @Param("pageSize") int pageSize) {
        return coffeeMapper.findAllWithParam(pageNum, pageSize);
    }

    public List<Coffee> pageFind2(RowBounds rowBounds) {
        return coffeeMapper.findAllWithRowBounds(rowBounds);
    }
}
